#######		REPLICATION FILES
#######		Climate Variability and Irregular Migration to the European Union
#######		Global Environmental Change
#######		Fabien Cottier and Idean Salehyan
#######		Replication: Appendix A.1
#######		This version: April 2021




# Set working directory
setwd("path/to/replication/directory")


# Load packages
library(dplyr)
library(tidyverse)


# load data
frontex <- readr::read_csv("FrontexIBCP_2009_2017m_cntr_df.csv")


##### Figure A.1: Eight largest irregular migrants sending countries

frontex <- frontex %>%
  dplyr::filter (year %in% 2010:2015)
df <- frontex %>%
  dplyr::filter (cowc>0, year %in% 2010:2015) %>%
  dplyr::group_by(cowc) %>%
  dplyr::summarise(
    nationality = first(nationality),
    nmigr = sum(nmigr,na.rm=T),
    nmigr_exbalk = sum(nmigr_exbalk ,na.rm=T)
  ) %>%
  dplyr::arrange(desc(nmigr_exbalk)) %>%
  head(8)
cowc_list <- unique(df$cowc)
cown_list <- unique(df$nationality)
frontex$date <- as.Date(paste(frontex$year,frontex$monthA,1),format = "%Y %b %d")


# create plot
plot.new()
plot.window(
  xlim=c(as.Date(c("2010-01-01", "2015-12-01"))),
  ylim=c(1, 5E5),
  log="y"
)
axis.Date(
  1,
  at = seq(as.Date("2010-01-01"), as.Date("2016-01-01"), "year")
)
at.y <- outer(1:9, 10^(0:5))[1:50]
lab.y <- ifelse(log10(at.y) %% 1 == 0, at.y, NA)
axis(
  2,
  at = at.y,
  labels = F
)
axis(
  2,
  at = c(1E1,1E2,1E3,1E4,1E5),
  labels = c("10","100","1,000","10,000","100,000"),
  lwd.ticks = 2
)
for (i in 1:length(cowc_list)){
  lines(
    frontex$date[frontex$cowc == cowc_list[i]],
    frontex$nmigr_exbalk[frontex$cowc == cowc_list[i]],
    col=i,
    lwd=2
  )
}
legend(
  "topleft",
  legend=cown_list,
  col = 1:10,
  lwd = 1,
  cex = .85,
  ncol = 3,
  bty = "n"
)





##### Table A.1: Number of irregular migration by country of origin over the period 2010-2015

tot_df <- frontex %>%
  dplyr::filter(!is.na(nmigr_exbalk)) %>%
  dplyr::group_by(cowc) %>%
  dplyr::summarise(
    nationality = first(nationality),
    nmigr_exbalk = sum(nmigr_exbalk)
  ) %>%
  dplyr::select(nationality, nmigr_exbalk) %>%
  dplyr::arrange(desc(nmigr_exbalk), nationality)

# print table
print(
  rbind(tot_df[tot_df$nationality != "Not specified", ], 
    tot_df[tot_df$nationality == "Not specified", ], 
    c("Total", sum(tot_df$nmigr_exbalk))
  ),
  n = nrow(tot_df)+1,
)